package controllers;

import models.data.Notendur;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.login;

/**
 * Created with IntelliJ IDEA.
 * User: bjornth
 * Date: 21.2.2013
 * Time: 14:31
 * To change this template use File | Settings | File Templates.
 */
public class AccountController extends Controller {

    public static class Login {

        public String kennitala;
        public String notandanr;

        //We need to validate the user information to make sure it is a valid user.
        public String validate() {
            if (Notendur.authenticate(kennitala, notandanr) == null) {
                return "Invalid user or password";
            }
            return null;
        }
    }

    final static Form<Login> userForm = form(Login.class);
    public static Result login() {
        return ok(login.render(userForm));
    }

    public static Result logout(){
        session().clear();
        flash("success", "Þú hefur verið skráð/ur út!");
        return redirect(routes.AccountController.login());
    }

    public static Result authenticate(){
        Form<Login> filledForm = userForm.bindFromRequest();
        //If the user is not valid we return a badrequest
        if (filledForm.hasErrors()) {
            return badRequest(login.render(filledForm));
        } else {
        //Otherwise we find information about the user that just logged in and store it in the session so we can get it in other classes.
            Notendur notandi = Notendur.find.where().eq("kennitala", filledForm.get().kennitala.toString()).eq("notandanr", filledForm.get().notandanr.toString()).findUnique();
            session().clear();
            session("kennitala", filledForm.get().kennitala);
            session("notandiId", notandi.notandi_id);
            session("skoliId", notandi.skoli_id);
            session("nafn", notandi.nafn);
            if(notandi.nemi != null){
                if(notandi.nemi == 1){
                    return redirect(routes.StudentController.studentDashboard());
                }
            }
            else{
                return redirect(routes.TeacherController.teacherDashboard());
            }
            return redirect(routes.TeacherController.teacherDashboard());
        }
    }


}
